const express = require("express");
const router = express.Router();
const menuController = require("../../controllers/menuController");
const { validateRequest } = require("../../middleware/validationMiddleware");
const { body, param, query } = require("express-validator");

// 创建菜单
router.post(
  "/menu",
  [
    body("name").notEmpty().withMessage("菜单名称不能为空"),
    body("parentId").optional().isInt().withMessage("父级菜单ID必须为整数"),
    body("path").optional().isString().withMessage("路由地址必须为字符串"),
    body("component").optional({nullable: true}).isString().withMessage("组件路径必须为字符串"),
    body("sort").optional().isInt().withMessage("排序值必须为整数"),
  ],
  validateRequest,
  menuController.createMenu
);

// 获取所有菜单
router.get(
  "/menu",
  [
    query("name").optional().isString().withMessage("菜单名称必须为字符串"),
  ],
  validateRequest,
  menuController.getMenuTree
);

// 获取Vue3路由格式的菜单树
router.get(
  "/menu/routes",
  validateRequest,
  menuController.getVueRoutes
);

// 获取角色菜单列表
router.get(
  "/menu/role/:roleId",
  [param("roleId").isInt().withMessage("无效的角色ID")],
  validateRequest,
  menuController.getRoleMenus
);

// 获取菜单下拉选项
router.get(
  "/menu/options",
  [
    query("onlyParent").optional().isBoolean().withMessage("onlyParent必须为布尔值"),
  ],
  validateRequest,
  menuController.getMenuOptions
);
// 更新菜单
router.put(
  "/menu/:id",
  [
    param("id").isInt().withMessage("无效的菜单ID"),
    body("name").optional().notEmpty().withMessage("菜单名称不能为空"),
    body("parent_id").optional().isInt().withMessage("父级菜单ID必须为整数"),
    body("path").optional().isString().withMessage("路由地址必须为字符串"),
    body("component").optional({nullable: true}).isString().withMessage("组件路径必须为字符串"),
    body("sort").optional().isInt().withMessage("排序值必须为整数"),
    body("status").optional().isIn([0, 1]).withMessage("状态值只能为0或1"),
  ],
  validateRequest,
  menuController.updateMenu
);

// 删除菜单
router.delete(
  "/menu/:id",
  [param("id").isInt().withMessage("无效的菜单ID")],
  validateRequest,
  menuController.deleteMenu
);

// 获取菜单详情（放在最后，避免捕获其他路由）
router.get(
  "/menu/:id",
  [param("id").isInt().withMessage("无效的菜单ID")],
  validateRequest,
  menuController.getMenuById
);

module.exports = router;
